import Vue from 'vue'
import { AjaxPlugin, ToastPlugin } from 'vux'
import router from './router'
import store from './store'
Vue.use(ToastPlugin)
const vm = new Vue()

AjaxPlugin.$http.defaults.baseURL = '/loans'

// http request 拦截器
AjaxPlugin.$http.interceptors.request.use(
	config => {
		config.headers = { ...config.headers, token: store.token }
		return config;
	},
	err => {
		return Promise.reject(err)
	})

AjaxPlugin.$http.interceptors.response.use(
	response => {
		const { code, msg } = response.data
		if (code === 401) router.replace('/login')
		else if (code !== 0) vm.$vux.toast.show({ text: msg, type: 'warn' })
		return response.data
	},
	error => {
		vm.$vux.toast.show({ text: '网络请求失败', type: 'warn' })
		return Promise.reject(error)
	})

Vue.use(AjaxPlugin)